package com.xuan.yubi.aop;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xuan.yubi.annotation.CountRecord;
import com.xuan.yubi.common.ErrorCode;
import com.xuan.yubi.exception.BusinessException;
import com.xuan.yubi.exception.ThrowUtils;
import com.xuan.yubi.model.entity.AiFrequency;
import com.xuan.yubi.model.entity.User;
import com.xuan.yubi.service.AiFrequencyService;
import com.xuan.yubi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
@Slf4j
public class IncrCountInterceptor {

    @Autowired
    private UserService userService;

    @Autowired
    private AiFrequencyService aiFrequencyService;

    @Around("@annotation(countRecord)")
    public Object incrementAiInvokeCount(ProceedingJoinPoint pjp, CountRecord countRecord) {
        // 1. 拿到当前 http 请求的 request
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        // 2. 查看当前用户状态是否被封号（不可调用 AI 服务）
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        loginUser = userService.getById(loginUser.getId());
        ThrowUtils.throwIf(loginUser.getUserStatus() == 1, ErrorCode.OPERATION_ERROR, "账号异常，请联系管理员");
        // 3. 查看当前用户是否还有剩余调用次数
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        QueryWrapper<AiFrequency> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", loginUser.getId());
        AiFrequency aiFrequency = aiFrequencyService.getOne(queryWrapper);
        // 记录为空，说明用户从未获取次数或未到个人信息查询次数
        ThrowUtils.throwIf(aiFrequency == null, ErrorCode.OPERATION_ERROR, "暂无分析次数，请到个人信息页获取");
        if (aiFrequency.getRemainFrequency() < 1) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "分析次数已用完，请到个人信息页获取");
        }

        Object proceed = null;
        try {
            proceed = pjp.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }

        // 4. 剩余调用次数 - 1，总调用次数 + 1
        aiFrequency.setRemainFrequency(aiFrequency.getRemainFrequency() - 1);
        aiFrequency.setTotalFrequency(aiFrequency.getTotalFrequency() + 1);
        aiFrequencyService.updateById(aiFrequency);
        return proceed;
    }
}
